<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" :placeholder="_transitionLanguages('placeholder', 'accountNumber')">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        :placeholder="_transitionLanguages('placeholder', 'password')"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)">
      {{ _transitionLanguages('basic', 'reset') }}
    </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      {{ _transitionLanguages('login', 'login') }}
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { HOME_URL } from '@/config';
import { getTimeState } from '@/utils';

import { ElNotification } from 'element-plus';
import { loginApi } from '@/api/modules/auth/login';
import { useUserStore } from '@/stores/modules/user';
import { useTabsStore } from '@/stores/modules/tabs';
import { useKeepAliveStore } from '@/stores/modules/keepAlive';
import { initDynamicRouter } from '@/routers/modules/dynamicRouter';
import { CircleClose, UserFilled } from '@element-plus/icons-vue';
import type { ElForm } from 'element-plus';
// import md5 from "md5";\
const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();

const _transitionLanguages = (v: string, l: string): string => {
  return transitionLanguages(v, l);
};

onMounted(() => {
  loginForm.username = localGet('login_username') || '';
  if (isDev()) {
    loginForm.username = 'root';
    loginForm.password = '123456';
  }
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === 'Enter' || e.code === 'enter' || e.code === 'NumpadEnter') {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

const loginRules = reactive({
  username: [{ required: true, message: _transitionLanguages('placeholder', 'accountNumber'), trigger: 'blur' }],
  password: [{ required: true, message: _transitionLanguages('placeholder', 'password'), trigger: 'blur' }]
});

const loading = ref(false);
const loginForm = reactive({
  username: '',
  password: ''
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口 md5(loginForm.password)
      const _data = await loginApi(loginForm);

      userStore.setToken(_data.tokenValue);
      userStore.setUserInfo(_data);

      localSet('login_username', loginForm.username);
      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(_data.nick),
        message: transitionLanguages('basic', 'loginSuccess'),
        type: 'success',
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped lang="scss">
@import '../index.scss';
</style>
